﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IdentityModel.Tokens;
using System.ServiceModel;
using System.Data;
using System.Configuration;
using System.Security.Cryptography.X509Certificates;

namespace SecurityTokenServiceNS
{
	public class DbConfiguration
	{
		private SqlConnection _sqlConnection = null;
		private static DbConfiguration _dbConfiguration = null;

		private DbConfiguration()
		{
			try
			{
				_sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["stsConStr"].ConnectionString);
			}
			catch (Exception)
			{
				throw new ConfigurationErrorsException("Error configuring STS DB connection!");
			}
		}

		public static DbConfiguration Current
		{
			get
			{
				if (_dbConfiguration == null)
					_dbConfiguration = new DbConfiguration();
				return _dbConfiguration;
			}
		}

		public SecurityToken GetRpToken(EndpointAddress appliesTo)
		{
			if (appliesTo == null)
				throw new ArgumentNullException("appliesTo");

			SqlCommand cmd = new SqlCommand("select certificate from RelyingParties where endpoint=@endpoint", _sqlConnection);
			cmd.Parameters.Add("@endpoint", SqlDbType.VarChar, 100).Value = appliesTo.Uri.ToString();
			_sqlConnection.Open();
			byte[] cert = (byte[])cmd.ExecuteScalar();
			_sqlConnection.Close();
			if(cert != null)
				return new X509SecurityToken(new X509Certificate2(cert));
			return null;
		}
		public List<ClaimMapping> GetMappingByEndpoint(EndpointAddress appliesTo)
		{
			if (appliesTo == null)
				throw new ArgumentNullException("appliesTo");

			List<ClaimMapping> list = new List<ClaimMapping>();

			SqlCommand cmd = new SqlCommand("select fromType, toType, fromValue, toValue from ClaimMapping"
				+"where endpoint=@endpoint and active=1", _sqlConnection);
			cmd.Parameters.Add("@endpoint", SqlDbType.VarChar, 100).Value = appliesTo.Uri.ToString();
			_sqlConnection.Open();
			SqlDataReader reader = cmd.ExecuteReader();

			while (reader.Read())
				list.Add(new ClaimMapping(reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString()));

			reader.Close();
			_sqlConnection.Close();

			return list;
		}
	}
}
